package com.mysoft.gfyx.marketdevelop.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.rpc.opensearch.OpensearchClientFactoryService;
import com.mysoft.gfyx.common.rpc.opensearch.OpensearchClientService;
import com.mysoft.gfyx.common.rpc.opensearch.dto.*;
import com.mysoft.gfyx.common.rpc.opensearch.dto.SearchMohurdProjectRequestDto;
import com.mysoft.gfyx.common.rpc.opensearch.dto.SearchPurchaseRequestDto;
import com.mysoft.gfyx.common.rpc.opensearch.dto.SearchSupplierRequestDto;
import com.mysoft.gfyx.common.rpc.opensearch.dto.SearchWinBidRequestDto;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.gfyx.common.time.impl.TimeServiceImpl;
import com.mysoft.gfyx.common.util.MyStringUtil;
import com.mysoft.gfyx.common.util.OpportunityUtil;
import com.mysoft.gfyx.common.ycg.YcgFileService;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.remoteService.*;
import com.mysoft.gfyx.marketdevelop.remoteService.dto.GetSubscriptionConfigRequestDto;
import com.mysoft.gfyx.marketdevelop.remoteService.dto.GetSubscriptionConfigResponseDto;
import com.mysoft.gfyx.marketdevelop.remoteService.dto.GetUserPermissionAreaResponseDto;
import com.mysoft.gfyx.marketdevelop.service.CommonService;
import com.mysoft.gfyx.marketdevelop.service.dto.SearchDeveloperProjectTypeDto;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImp extends AppService implements com.mysoft.gfyx.marketdevelop.service.SearchService {

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Resource
    private YcgFileService ycgFileService;

    @Autowired
    private RemoteClueService remoteClueService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private RemoteDataPermissionService remoteDataPermissionService;

    @Autowired
    private com.mysoft.gfyx.marketdevelop.service.CommonService commonService;

    @Autowired
    private OpportunityUtil opportunityUtil;

    @Autowired
    private OpensearchClientFactoryService opensearchClientFactoryService;

    @Autowired
    private com.mysoft.gfyx.marketdevelop.service.MohurdProjectService mohurdProjectService;

    @Autowired
    private com.mysoft.gfyx.marketdevelop.service.SupplierService supplierService;

    @Autowired
    private com.mysoft.gfyx.marketdevelop.service.LabelService labelService;

    @Autowired
    private com.mysoft.gfyx.marketdevelop.service.ProvinceRadarService provinceRadarService;

    @Autowired
    private RemoteSubscriptionService remoteSubscriptionService;


    public FieldsSetting loadSearchDeveloperFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("organizing_code");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_developer";
        fieldsSetting.getFields().add(new DataApiField(com.mysoft.gfyx.marketdevelop.mip.dto.SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_nameHL", groupName, "高亮客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "开发商Logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("legal_name", groupName, "企业法人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("regist_capi", groupName, "注册资本", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("establish_date", groupName, "成立日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "详细地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_type", groupName, "项目类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage_category", groupName, "土地类型分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_type", groupName, "土地类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("taken_land_area", groupName, "近一年拿地", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("open_project_num", groupName, "近一年开盘", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_num", groupName, "近一年采购", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_num", groupName, "近一年合作", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("purchase_contact_cnt", groupName, "联系人数量", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("listed_enterprises_label", groupName, "上市标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("business_status_label", groupName, "经营状态标签", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("top_company_summary", groupName, "顶级公司", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("has_added", groupName, "是否已添加过客户", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("commence_permit_cnt", groupName, "开工数量", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("commence_permit_cnt_1year", groupName, "近一年开工", FieldType.Decimal));

        fieldsSetting.getFields().add(new DataApiField("developer_activity_label", groupName, "活跃采购商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_ycg_certification", groupName, "平台认证", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_ycg_offline_business_connect", groupName, "供需对接会", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_level_tag", groupName, "企业等级", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tags_set", groupName, "企业标签", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("developer_top_100_label", groupName, "地产百强标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_decorate_expand_label", groupName, "新精装客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_land_usage_expand_label", groupName, "新住宅客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_area_expand_label", groupName, "新区域拓展标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("high_project_customers_label", groupName, "高端项目客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category", groupName, "行业分类(1类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_big", groupName, "行业分类(2类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_middle", groupName, "行业分类(3类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_small", groupName, "行业分类(4类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("new_house_sale_2year", groupName, "近两年新房销售", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_score", groupName, "好客户得分", FieldType.Int));
        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchDeveloperData(LoadDataParams options) {
        GetSubscriptionConfigRequestDto getSubscriptionConfigRequestDto = new GetSubscriptionConfigRequestDto();
        getSubscriptionConfigRequestDto.setType(GetSubscriptionConfigRequestDto.SubscriptionType.RadarSubscription);
        GetSubscriptionConfigResponseDto config = remoteSubscriptionService.getSubscriptionConfig(getSubscriptionConfigRequestDto);
        String landUsage = "";
        String projectLable = "";
        if (config != null) {
            landUsage = config.getLandUsage();
            projectLable = config.getProjectType();
        }

        SearchDeveloperRequestDto dto = new SearchDeveloperRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        List<Filter> filters = options.getOptions().getFilters();
        filters = labelService.setLandUsageLabel(filters, "land_type");
        dto.addFilterByLoadDataApi(filters);

        // 这里用省市的组合查询,不适用单省市的精准查询
        String area = "";
        if (dto.getProvince() != null && !dto.getProvince().equals("")) {
            area += dto.getProvince();
        }
        if (dto.getCity() != null && !dto.getCity().equals("")) {
            if (!area.equals("")) {
                area += ",";
            }
            area += dto.getCity();
        }
        dto.setArea(area);
        dto.setCity("");
        dto.setProvince("");

        dto.setSubscription_land_usage(landUsage);
        dto.setSubscription_project_type(projectLable);
        //调用opensearch
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.searchDeveloperPost(dto);
        // 获取是否添加过客户
        List<String> creditCodes = res.getData().getList().stream().map(p -> {
            if (p.get("organizing_code") != null) {
                return p.get("organizing_code").toString();
            } else {
                return "";
            }
        }).collect(Collectors.toList());
        Set<String> haveAdded = remoteCustomerService.isAdded(creditCodes);

        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(d -> {
            if (d.get("organizing_code") != null) {
                idList.add(d.get("organizing_code").toString());
            }
            // 处理Logo
            if (d.get("developer_id") != null && d.get("developer_logo") != null) {
                d.put("developer_logo", ycgFileService.getEnterpriseLogo(d.get("developer_id").toString(), d.get("developer_logo").toString()));
            }

            // 成立时间
            try {
                SimpleDateFormat establishDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date establishDate = establishDateFormat.parse(d.getOrDefault("establish_date", "").toString());
                d.put("establish_date", establishDateFormat.format(establishDate));
            } catch (java.text.ParseException e) {
                d.put("establish_date", "-");
            }

            // 注册资本
            if (d.get("regist_capi") != null) {
                d.put("regist_capi", d.get("regist_capi").toString() + d.getOrDefault("regist_capi_unit", "万元"));
            }

            // 顶级公司
            if (d.get("top_organizing_code") != null) {
                if (d.get("top_company_type_label") != null && !d.get("top_company_type_label").equals("")) {
                    d.put("top_company_summary", d.get("top_developer_name") + "【" + d.get("top_company_type_label") + "】");
                } else {
                    d.put("top_company_summary", d.get("top_developer_name"));
                }
            } else {
                d.put("top_company_summary", "");
            }

            // 处理标签
            if (d.get("project_type") != null) {
                Object projectType = d.get("project_type");
                if (projectType instanceof ArrayList<?>) {
                    ArrayList<String> projectTypeStringsList = new ArrayList<>();
                    for (Object pt : (List<?>) projectType) {

                        ObjectMapper objectMapper = new ObjectMapper();
                        SearchDeveloperProjectTypeDto searchDeveloperProjectTypeDto = objectMapper.convertValue(pt, SearchDeveloperProjectTypeDto.class);
                        if (searchDeveloperProjectTypeDto.getProject_type_label() == null) {
                            continue;
                        }
                        projectTypeStringsList.add(searchDeveloperProjectTypeDto.getProject_type_label());

                    }
                    String projectTypeString = String.join(",", projectTypeStringsList);
                    d.put("project_type", projectTypeString);

                }
            }

            // 是否添加过
            if (d.get("organizing_code") != null) {
                int hasAdded = haveAdded.contains(d.getOrDefault("organizing_code", "").toString()) ? 1 : 0;
                d.put("has_added", hasAdded);
            }

            // 处理土地类型标签
            if (d.get("land_usage_type_label_arr") != null) {
                d.put("land_type", labelService.loadLandUsageLabel(d.get("land_usage_type_label_arr"), "project_type_label"));
            }

            //近2年销售额,将 数字转为字符串,单位也由"元"转成"万元",小数点后保存2位
            if (d.get("new_house_sale_2year") != null && !d.get("new_house_sale_2year").equals(0)) {
                d.put("new_house_sale_2year", d.get("new_house_sale_2year") + "万元");
            } else {
                d.put("new_house_sale_2year", "--");
            }
        });

        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.DEVELOPER.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("organizing_code") != null && opptyStatus.containsKey(r.get("organizing_code").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("organizing_code").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        ListDataResult result = new ListDataResult();
        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

    public FieldsSetting loadSearchOpportunityFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_oppo";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField(com.mysoft.gfyx.marketdevelop.mip.dto.SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "招标单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("title", groupName, "标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("publish_time", groupName, "发布时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("data_source", groupName, "信息类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("data_source_code", groupName, "信息类型Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("end_time", groupName, "截止时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("bidding_service_category", groupName, "服务分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("status", groupName, "采购状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("owner", groupName, "招标负责人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("owner_mobile", groupName, "招标负责人电话", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("phone_type", groupName, "招标负责人电话类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_name", groupName, "项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("has_added", groupName, "是否已添加过线索", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("purchase_amount", groupName, "采购预算", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_cnt_1year", groupName, "关联招标", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_cnt", groupName, "合作单位", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchOpportunityData(LoadDataParams options) {
        SearchPurchaseRequestDto dto = new SearchPurchaseRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());

        if ((dto.getProvince_code() == null || dto.getProvince_code().equals("")) && (dto.getCity_code() == null || dto.getCity_code().equals(""))) {
            //用户没有选择省市，那么就用用户有权益和权限的省市作为筛选条件
            dto.setArea(this.getProfitAndPermissionAreaCodeStr());
        } else {
//            // 用户选择了省市,将用户选择的省市添加到area中组合查询
//            String area = "";
//            if (dto.getProvince_code() != null && !dto.getProvince_code().equals("")) {
//                area += dto.getProvince_code();
//            }
//            if (dto.getCity_code() != null && !dto.getCity_code().equals("")) {
//                if (!area.equals("")) {
//                    area += ",";
//                }
//                area += dto.getCity_code();
//            }
//            dto.setArea(area);
//            dto.setCity_code("");
//            dto.setProvince_code("");
        }
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.searchPurchase(dto);
        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        // 获取是否添加过线索
        List<String> purchasesId = res.getData().getList().stream().map(p -> p.get("id").toString()).collect(Collectors.toList());
        Set<String> haveAdded = remoteClueService.isAdded(purchasesId);

        TimeService timeService = new TimeServiceImpl();
        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null) {
                idList.add(r.get("id").toString());
            }
            // 处理 logo
            if (r.get("developer_id") != null && r.get("developer_logo") != null) {
                r.put("developer_logo", ycgFileService.getEnterpriseLogo(r.get("developer_id").toString(), r.get("developer_logo").toString()));
            }
            // 处理项目名称
            if (r.get("projects") != null) {
                r.put("project_name", this.spellProjectName(r.get("projects")));
            }
            // 处理招标负责人名称
            if (r.get("ower") != null) {
                r.put("owner", MyStringUtil.ReplaceSpecifiedStr(0, 1, r.get("ower").toString(), "*", 2));
            }
            if (r.get("ower_mobile") != null) {
                r.put("owner_mobile", this.handleOwnerPhone(r.get("ower_mobile"), r.getOrDefault("data_source_code", "")));
            }
            if (r.get("end_time") != null) {
                r.put("status", opportunityUtil.getStatusFromEndTime(r.get("end_time").toString()));
            }
            // 招标发布时间处理
            if (r.get("data_source_code") != null && "trading_center".equals(r.get("data_source_code"))) {
                // publish_time -> 2022-09-28 16:44:36
                if (!Objects.equals(r.getOrDefault("publish_time", "").toString(), "")) {
                    r.put("publish_time", timeService.convertTimeFormat(r.getOrDefault("publish_time", "").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
                }
            }

            // 是否添加过
            if (r.get("id") != null) {
                int hasAdded = haveAdded.contains(r.get("id").toString()) ? 1 : 0;
                r.put("has_added", hasAdded);
            }

            // 关联招标和合作单位
            if (r.get("purchase_demand_cnt_1year") != null && !r.get("purchase_demand_cnt_1year").equals("")) {
                r.put("purchase_demand_cnt_1year", r.get("purchase_demand_cnt_1year") + "条");
            }
            if (r.get("cooperation_enterprise_cnt") != null && !r.get("cooperation_enterprise_cnt").equals("")) {
                r.put("cooperation_enterprise_cnt", r.get("cooperation_enterprise_cnt") + "家");
            }

            // 处理省市
            if (r.get("projects") != null) {
                com.mysoft.gfyx.marketdevelop.mip.dto.OpportunityProjectDto projectDto = this.getProvinceAndCityFromProject(r.get("projects"));
                r.put("city", projectDto.getCity());
                r.put("province", projectDto.getProvince());
            } else {
                r.put("city", "");
                r.put("province", "");
            }

        });
        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.PURCHASE.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null && opptyStatus.containsKey(r.get("id").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("id").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

    @Override
    public com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionPageDto getLatestOpportunity(com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionReqDto reqDto) {
        SearchPurchaseRequestDto dto = new SearchPurchaseRequestDto();
        dto.setPage(reqDto.getPage());
        dto.setPage_size(reqDto.getPageSize());
        dto.addFilterByLoadDataApi(null);
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        //请求opensearch
        OpenSearchListResponseDto resp = service.searchPurchase(dto);
        com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionPageDto result = new com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionPageDto();
        List<com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionDto> data = new ArrayList<>();
        result.setPage(reqDto.getPage());
        result.setPageSize(reqDto.getPageSize());
        if (resp.getData() == null || resp.getData().getList() == null) {
            result.setTotal(0);
            result.setData(data);
            return result;
        }


        result.setTotal(resp.getData().getTotal());
        resp.getData().getList().forEach(r -> {
            com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionDto item = new com.mysoft.gfyx.marketdevelop.mip.dto.MySubscriptionDto();
            item.setTitle(r.get("title").toString());
            item.setPublishTime(r.get("publish_time").toString());
            item.setDeveloperName(r.get("developer_name").toString());
            item.setSubscriptionUID(r.get("id").toString());
            item.setLicenseCode(r.get("organizing_code").toString());
            item.setOpSubscriptionGUID(null);
            item.setSource("es");
            item.setMobile(r.get("ower_mobile").toString());
            item.setContact(r.get("ower").toString());
            item.setServiceCategory(r.get("bidding_service_category").toString());
            item.setType(r.get("data_source").toString());
            // 判断是否有项目信息
            com.mysoft.gfyx.marketdevelop.mip.dto.OpportunityProjectDto projectDto = this.getProvinceAndCityFromProject(r.get("projects"));
            item.setProvince(projectDto.getProvince());
            item.setCity(projectDto.getCity());
            // 设置logo信息
            item.setDeveloperLogo(ycgFileService.getEnterpriseLogo(r.get("developer_id").toString(), r.get("developer_logo").toString()));
            data.add(item);
            // 设置状态
            item.setStatus(opportunityUtil.getStatusFromEndTime(r.get("end_time").toString()));
        });
        result.setData(data);

        return result;
    }

    public String spellProjectName(Object projectObj) {
        String projectName = "";
        List<Map<String, String>> projects = (List<Map<String, String>>) projectObj;
        if (projects != null && projects.size() > 0) {
            Iterator<Map<String, String>> it = projects.iterator();
            List<String> projectStr = new LinkedList<>();
            while (it.hasNext()) {
                Map<String, String> s = it.next();
                projectStr.add(s.get("project_name"));
            }
            projectName = String.join(",", projectStr);
        } else {
            projectName = "--";
        }
        return projectName;
    }

    public com.mysoft.gfyx.marketdevelop.mip.dto.OpportunityProjectDto getProvinceAndCityFromProject(Object projectObj) {
        com.mysoft.gfyx.marketdevelop.mip.dto.OpportunityProjectDto dto = new com.mysoft.gfyx.marketdevelop.mip.dto.OpportunityProjectDto();
        dto.setProvince("--");
        dto.setCity("--");
        List<Map<String, String>> projects = (List<Map<String, String>>) projectObj;
        if (projects != null && projects.size() > 0) {
            Iterator<Map<String, String>> it = projects.iterator();
            List<String> projectStr = new LinkedList<>();
            while (it.hasNext()) {
                Map<String, String> s = it.next();
                dto.setProvince(s.get("province"));
                dto.setCity(s.get("city"));
            }
        }

        return dto;
    }

    public FieldsSetting loadSearchTakenLandFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_land";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField(com.mysoft.gfyx.marketdevelop.mip.dto.SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "拿地企业", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_nameHL", groupName, "高亮客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_title", groupName, "标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_titleHL", groupName, "高亮标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("take_land_date", groupName, "拿地时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "企业Logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_and_city", groupName, "省与城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage_category", groupName, "土地标签分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage", groupName, "土地类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage_label", groupName, "土地类型标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("all_area", groupName, "土地面积", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("land_unit_price", groupName, "土地单价", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("take_land_price", groupName, "成交价格", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_cnt_1year", groupName, "关联招标", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_cnt", groupName, "合作单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_price_gt_avg", groupName, "高端项目标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contact_num", groupName, "联系人数量", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchTakenLandData(LoadDataParams options) {
        SearchTakeLandRequestDto dto = new SearchTakeLandRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        List<Filter> filters = options.getOptions().getFilters();
        filters = labelService.setLandUsageLabel(filters, "land_usage_label");
        dto.addFilterByLoadDataApi(filters);

        if ((dto.getProvince() == null || dto.getProvince().equals("")) && (dto.getCity() == null || dto.getCity().equals(""))) {
            //用户没有选择省市，那么就用用户有权益和权限的省市作为筛选条件
            dto.setArea(this.getProfitAndPermissionAreaCodeStr());
        } else {
            // 用户选择了省市,将用户选择的省市添加到area中组合查询
            String area = "";
            if (dto.getProvince() != null && !dto.getProvince().equals("")) {
                area += dto.getProvince();
            }
            if (dto.getCity() != null && !dto.getCity().equals("")) {
                if (!area.equals("")) {
                    area += ",";
                }
                area += dto.getCity();
            }
            dto.setArea(area);
            dto.setCity("");
            dto.setProvince("");
        }
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.searchTakenLand(dto);

        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        TimeService timeService = new TimeServiceImpl();
        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null) {
                idList.add(r.get("id").toString());
            }

            // 处理Logo
            if (r.get("developer_id") != null && r.get("developer_logo") != null) {
                r.put("developer_logo", ycgFileService.getEnterpriseLogo(r.get("developer_id").toString(), r.get("developer_logo").toString()));
            }

            if (r.get("take_land_date") != null && !r.get("take_land_date").equals("")) {
                r.put("take_land_date", timeService.convertTimeFormat(r.get("take_land_date").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            r.putIfAbsent("developer_nameHL", "");
            r.putIfAbsent("land_titleHL", "");
            r.putIfAbsent("province", "");
            r.putIfAbsent("city", "");
            if (r.get("province") != null && r.get("city") != null) {
                if (r.get("province").equals(r.get("city"))) {
                    r.put("province_and_city", r.get("province"));
                } else {
                    r.put("province_and_city", r.get("province").toString() + r.get("city").toString());
                }
            } else {
                r.put("province_and_city", "");
            }
            // 关联招标和合作单位
            if (r.get("purchase_demand_cnt_1year") != null && !r.get("purchase_demand_cnt_1year").equals("")) {
                r.put("purchase_demand_cnt_1year", r.get("purchase_demand_cnt_1year") + "条");
            }
            if (r.get("cooperation_enterprise_cnt") != null && !r.get("cooperation_enterprise_cnt").equals("")) {
                r.put("cooperation_enterprise_cnt", r.get("cooperation_enterprise_cnt") + "家");
            }
            // 处理土地标签
            if (r.get("land_usage_label") != null) {
                r.put("land_usage_label", labelService.loadLandUsageLabel(r.get("land_usage_label"), "label"));
                //前端取值是land_usage，这里保持一致
                r.put("land_usage", labelService.loadLandUsageLabel(r.get("land_usage_label"), "label"));
            }
            //todo 联系人数量
            r.put("contact_num", 0);
        });

        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.LAND.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null && opptyStatus.containsKey(r.get("id").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("id").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());
        return result;
    }

    public FieldsSetting loadSearchWinBidFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_win_bid";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_name", groupName, "拿地企业", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_nameHL", groupName, "高亮客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("title", groupName, "标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("titleHL", groupName, "高亮标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("publish_time", groupName, "发布时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("first_winbid_supplier_name", groupName, "中标公司一", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("second_winbid_supplier_name", groupName, "中标公司二", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("third_winbid_supplier_name", groupName, "中标公司三", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("first_winbid_supplier_nameHL", groupName, "中标公司一 高亮", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("second_winbid_supplier_nameHL", groupName, "中标公司二 高亮", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("third_winbid_supplier_nameHL", groupName, "中标公司三 高亮", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("all_winbid_supplier_nameHL", groupName, "中标公司组合 高亮", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("first_winbid_price", groupName, "中标金额", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("source_type", groupName, "类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("source", groupName, "来源", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("source_sub", groupName, "子来源", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchWinBidData(LoadDataParams options) {
        SearchWinBidRequestDto dto = new SearchWinBidRequestDto();
        //dto.setKeyword(creditCode);
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        if ((dto.getProvince_code() == null || dto.getProvince_code().equals("")) && (dto.getCity_code() == null || dto.getCity_code().equals(""))) {
            //用户没有选择省市，那么就用用户有权益和权限的省市作为筛选条件
            dto.setArea(this.getProfitAndPermissionAreaCodeStr());
        } else {
            // 用户选择了省市,将用户选择的省市添加到area中组合查询
//            String area = "";
//            if (dto.getProvince_code() != null && !dto.getProvince_code().equals("")) {
//                area += dto.getProvince_code();
//            }
//            if (dto.getCity_code() != null && !dto.getCity_code().equals("")) {
//                if (!area.equals("")) {
//                    area += ",";
//                }
//                area += dto.getCity_code();
//            }
//            dto.setArea(area);
//            dto.setCity_code("");
//            dto.setProvince_code("");
        }
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.winBidGetList(dto);

        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        TimeService timeService = new TimeServiceImpl();
        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null) {
                idList.add(r.get("id").toString());
            }

            if (r.get("publish_time") != null && !r.get("publish_time").equals("")) {
                r.put("publish_time", timeService.convertTimeFormat(r.get("publish_time").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            r.putIfAbsent("company_nameHL", "");
            r.putIfAbsent("titleHL", "");
            r.putIfAbsent("first_winbid_supplier_nameHL", r.getOrDefault("first_winbid_supplier_name", ""));
            r.putIfAbsent("second_winbid_supplier_nameHL", r.getOrDefault("second_winbid_supplier_nameHL", ""));
            r.putIfAbsent("third_winbid_supplier_nameHL", r.getOrDefault("third_winbid_supplier_nameHL", ""));

            Set<String> allSuppliers = new HashSet<>();
            if (!StringUtil.isBlank(r.get("first_winbid_supplier_nameHL").toString()))
                allSuppliers.add(r.get("first_winbid_supplier_nameHL").toString());
            if (!StringUtil.isBlank(r.get("second_winbid_supplier_nameHL").toString()))
                allSuppliers.add(r.get("second_winbid_supplier_nameHL").toString());
            if (!StringUtil.isBlank(r.get("third_winbid_supplier_nameHL").toString()))
                allSuppliers.add(r.get("third_winbid_supplier_nameHL").toString());

            r.put("all_winbid_supplier_nameHL", StringUtil.join(allSuppliers, ","));
            r.putIfAbsent("province", "");
            r.putIfAbsent("city", "");
            if (r.get("province") != null && r.get("city") != null) {
                if (r.get("province").equals(r.get("city"))) {
                    r.put("province_and_city", r.get("province"));
                } else {
                    r.put("province_and_city", r.get("province").toString() + r.get("city").toString());
                }
            } else {
                r.put("province_and_city", "");
            }


        });
        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.WINBID.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null && opptyStatus.containsKey(r.get("id").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("id").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

    public FieldsSetting loadSearchCommencePermitFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_working";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField(com.mysoft.gfyx.marketdevelop.mip.dto.SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "建设单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_nameHL", groupName, "高亮客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "开发商Logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_name", groupName, "项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_nameHL", groupName, "高亮项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("construction_unit", groupName, "施工单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("construction_unitHL", groupName, "高亮施工单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("start_time", groupName, "开工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_and_city", groupName, "省份城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("completed_time", groupName, "竣工日期", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("construction_area", groupName, "施工面积", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("contract_price", groupName, "合同金额", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_cnt_1year", groupName, "关联招标", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_cnt", groupName, "合作单位", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchCommencePermitData(LoadDataParams options) {
        com.mysoft.gfyx.marketdevelop.mip.dto.SearchCommencePermitRequestDto dto = new com.mysoft.gfyx.marketdevelop.mip.dto.SearchCommencePermitRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        dto.setProvince_code(commonService.checkProvinceProfit(dto.getProvince_code()));
        dto.setCity_code(commonService.checkCityProfit(dto.getCity_code()));
        com.mysoft.gfyx.marketdevelop.mip.dto.BasicOpensearchResponse res = getDeveloperDataService.searchCommencePermit(dto.getKeyword(), dto.getProvince_code(), dto.getCity_code(), dto.getCompany_type_label(), dto.getAreaLower(), dto.getAreaUpper(), dto.getPriceLower(), dto.getPriceUpper(), dto.getBeginLower(), dto.getBeginUpper(), dto.getFinishLower(), dto.getFinishUpper(), dto.getPage(), dto.getPageSize());

        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        TimeService timeService = new TimeServiceImpl();
        res.getData().getList().forEach(r -> {
            // 处理Logo
            r.put("developer_logo", ycgFileService.getEnterpriseLogo(r.get("developer_id").toString(), r.get("developer_logo").toString()));

            if (r.get("start_time") != null && !r.get("start_time").equals("")) {
                r.put("start_time", timeService.convertTimeFormat(r.get("start_time").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            if (r.get("completed_time") != null && !r.get("completed_time").equals("")) {
                r.put("completed_time", timeService.convertTimeFormat(r.get("completed_time").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            r.putIfAbsent("developer_nameHL", "");
            r.putIfAbsent("project_nameHL", "");
            r.putIfAbsent("construction_unitHL", "");
            r.putIfAbsent("province", "");
            r.putIfAbsent("city", "");
            if (r.get("province").equals(r.get("city"))) {
                r.put("province_and_city", r.get("province"));
            } else {
                r.put("province_and_city", r.get("province").toString() + r.get("city").toString());
            }

            // 关联招标和合作单位
            if (r.get("purchase_demand_cnt_1year") != null && !r.get("purchase_demand_cnt_1year").equals("")) {
                r.put("purchase_demand_cnt_1year", r.get("purchase_demand_cnt_1year") + "条");
            }
            if (r.get("cooperation_enterprise_cnt") != null && !r.get("cooperation_enterprise_cnt").equals("")) {
                r.put("cooperation_enterprise_cnt", r.get("cooperation_enterprise_cnt") + "家");
            }
        });


        result.setData(res.getData().getList());
        // result.setTotal(this.limitMaxPage(res.getData().getTotal(), options.getPageSize()));
        result.setTotal(res.getData().getTotal());

        return result;
    }

    public FieldsSetting loadSearchProjectFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());

        String groupName = "developer_search_working";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField(com.mysoft.gfyx.marketdevelop.mip.dto.SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "开发商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "开发商Logo", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_and_city", groupName, "省份城市", FieldType.String));

//        fieldsSetting.getFields().add(new DataApiField("developer_nameHL", groupName, "高亮客户名称", FieldType.String));
//        fieldsSetting.getFields().add(new DataApiField("project_titleHL", groupName, "高亮项目名称", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("project_title", groupName, "项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("opening_time", groupName, "开盘日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("delivery_time", groupName, "交房日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("property_category_label", groupName, "项目类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("fitment_fee_label", groupName, "装修状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_price_gt_avg", groupName, "高端项目标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_cnt_1year", groupName, "关联招标", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_cnt", groupName, "合作单位", FieldType.String));

        // 新房销售数据
        fieldsSetting.getFields().add(new DataApiField("new_house_deal_num", groupName, "已售总套数", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("new_house_deal_money", groupName, "已售总金额", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("new_house_sale_rate", groupName, "去化率", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchProjectData(LoadDataParams options) {
        SearchProjectRequestDto dto = new SearchProjectRequestDto();

        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        if ((dto.getProvince_code() == null || dto.getProvince_code().equals("")) && (dto.getCity_code() == null || dto.getCity_code().equals(""))) {
            //用户没有选择省市，那么就用用户有权益和权限的省市作为筛选条件
            dto.setArea(this.getProfitAndPermissionAreaCodeStr());
        } else {
            // 用户选择了省市,将用户选择的省市添加到area中组合查询
            String area = "";
            if (dto.getProvince_code() != null && !dto.getProvince_code().equals("")) {
                area += dto.getProvince_code();
            }
            if (dto.getCity_code() != null && !dto.getCity_code().equals("")) {
                if (!area.equals("")) {
                    area += ",";
                }
                area += dto.getCity_code();
            }
            dto.setArea(area);
            dto.setCity_code("");
            dto.setProvince_code("");
        }
//
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        //请求opensearch
        OpenSearchListResponseDto res = service.searchProject(dto);
        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        TimeService timeService = new TimeServiceImpl();
        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null) {
                idList.add(r.get("id").toString());
            }
            // 处理Logo
            if (r.get("developer_id") != null && r.get("developer_logo") != null) {
                r.put("developer_logo", ycgFileService.getEnterpriseLogo(r.get("developer_id").toString(), r.get("developer_logo").toString()));
            }

            if (r.get("opening_time") != null && !r.get("opening_time").equals("")) {
                r.put("opening_time", timeService.convertTimeFormat(r.get("opening_time").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            if (r.get("delivery_time") != null && !r.get("delivery_time").equals("")) {
                r.put("delivery_time", timeService.convertTimeFormat(r.get("delivery_time").toString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
            }

            r.putIfAbsent("developer_nameHL", "");
            r.putIfAbsent("project_titleHL", "");
            r.putIfAbsent("province", "");
            r.putIfAbsent("city", "");

            if (r.get("province") != null && r.get("city") != null) {
                if (r.get("province").equals(r.get("city"))) {
                    r.put("province_and_city", r.get("province"));
                } else {
                    r.put("province_and_city", r.get("province").toString() + r.get("city").toString());
                }
            }

            // 关联招标和合作单位
            if (r.get("purchase_demand_cnt_1year") != null && !r.get("purchase_demand_cnt_1year").equals("")) {
                r.put("purchase_demand_cnt_1year", r.get("purchase_demand_cnt_1year") + "条");
            }
            if (r.get("cooperation_enterprise_cnt") != null && !r.get("cooperation_enterprise_cnt").equals("")) {
                r.put("cooperation_enterprise_cnt", r.get("cooperation_enterprise_cnt") + "家");
            }


            if (r.get("new_house_deal_num") == null || r.get("new_house_deal_num").equals("")) {
                r.put("new_house_deal_num", "--");
            } else {
                r.put("new_house_deal_num", r.get("new_house_deal_num") + "套");
            }

            if (r.get("new_house_deal_money") == null || r.get("new_house_deal_money").equals("")) {
                r.put("new_house_deal_money", "--");
            } else {
                r.put("new_house_deal_money", r.get("new_house_deal_money") + "万元");
            }

            if (r.get("new_house_sale_rate") == null || r.get("new_house_sale_rate").equals("")) {
                r.put("new_house_sale_rate", "--");
            } else {
                r.put("new_house_sale_rate", r.get("new_house_sale_rate") + "%");
            }

        });
        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.SALE.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null && opptyStatus.containsKey(r.get("id").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("id").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

    private String getProfitAndPermissionAreaCodeStr() {
        GetUserPermissionAreaResponseDto userProvincePermissionDto = remoteDataPermissionService.getUserPermissionArea();
        //如果用户选择了省份,则直接用用户选择的省份返回
        if (userProvincePermissionDto == null || userProvincePermissionDto.getArea() == null || userProvincePermissionDto.getArea().contains("0") || userProvincePermissionDto.getArea().size() == 0) {
            //用户有全国权限或者没有设置权限,不指定查询的省份
            return "";
        }

        return String.join(",", userProvincePermissionDto.getArea());
    }


    private String handleOwnerPhone(Object ownerPhone, Object sourceCode) {
        String phoneStr = ownerPhone.toString();
        String[] sourceArr = {"website_bid", "trading_center", "czsaas_bid"};
        if (phoneStr.length() > 0 && Arrays.asList(sourceArr).contains(sourceCode.toString())) {
            return "添加线索后，进入线索管理查看";
        } else {
            return "--";
        }
    }

    public FieldsSetting loadSearchMohurdProjectFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "search_mohurd_project";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "主键id", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_num", groupName, "项目编码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_name", groupName, "项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("build_corp_name", groupName, "建设单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "建设单位信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "建设单位logo", FieldType.Picture));

        fieldsSetting.getFields().add(new DataApiField("prj_property_num", groupName, "建设性质", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_function_num", groupName, "工程用途", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_type_num", groupName, "项目分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tender_result_date", groupName, "中标日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("update_time", groupName, "更新日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("all_invest", groupName, "总投资(万)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_size", groupName, "建筑规模", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("conscorp_name", groupName, "施工单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "项目地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_approval_date", groupName, "立项日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contract_date", groupName, "合同签订日期", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("release_date", groupName, "开工许可证发证日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("licence_check_depart_name", groupName, "发证机关", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("builder_licence_num", groupName, "施工许可证编号", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("begin_date", groupName, "计划开工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("end_date", groupName, "计划竣工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("b_date", groupName, "实际开工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("e_date", groupName, "实际竣工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("county", groupName, "县（区）", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("time_type", groupName, "时间类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("time_begin", groupName, "开始时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("time_end", groupName, "结束时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label_string", groupName, "企业类型(字符串)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_developer_name", groupName, "顶级公司", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_organizing_code", groupName, "顶级公司信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_company_type_label", groupName, "顶级公司企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_company_type_label_string", groupName, "顶级公司企业类型(字符串)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_and_city", groupName, "省市区", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("contact_cnt", groupName, "联系方式(数量)", FieldType.String)); //已废弃
        fieldsSetting.getFields().add(new DataApiField("contact_num", groupName, "联系方式(推荐)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("bidding_cnt", groupName, "招投标(数量)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contract_cnt", groupName, "合同登记(数量)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("construction_cnt", groupName, "施工图审(数量)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("license_cnt", groupName, "开工许可(数量)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("completion_check_cnt", groupName, "竣工验收(数量)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("completion_record_cnt", groupName, "竣工备案(数量)", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("is_price_gt_avg", groupName, "高端项目标签", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchMohurdProjectData(LoadDataParams options) {
        SearchMohurdProjectRequestDto dto = new SearchMohurdProjectRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        if ((dto.getProvince_code() == null || dto.getProvince_code().equals("")) && (dto.getCity_code() == null || dto.getCity_code().equals(""))) {
            //用户没有选择省市，那么就用用户有权益和权限的省市作为筛选条件
            dto.setArea(this.getProfitAndPermissionAreaCodeStr());
        } else {
            // 用户选择了省市,将用户选择的省市添加到area中组合查询
            String area = "";
            if (dto.getProvince_code() != null && !dto.getProvince_code().equals("")) {
                area += dto.getProvince_code();
            }
            if (dto.getCity_code() != null && !dto.getCity_code().equals("")) {
                if (!area.equals("")) {
                    area += ",";
                }
                area += dto.getCity_code();
            }
            dto.setArea(area);
            dto.setCity_code("");
            dto.setProvince_code("");
        }
        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.searchMohurdProject(dto);

        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        List<String> organizingCodeList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(p -> {
            if (p.get("id") != null) {
                idList.add(p.get("id").toString());
            }
            mohurdProjectService.processMohurdProject(p, 2);
            if (p.get("organizing_code_string") != null && !p.get("organizing_code_string").equals("")) {
                organizingCodeList.add(p.get("organizing_code_string").toString());
            }
        });
        //联系人数量
        com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperContactsRequestDto getDeveloperContactsRequestDto = new com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperContactsRequestDto();
        getDeveloperContactsRequestDto.setDeveloper_organizing_code(organizingCodeList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        getDeveloperContactsRequestDto.setPageSize(100000);
        Map<String, Integer> contactCount = provinceRadarService.getContactCount(getDeveloperContactsRequestDto);
        res.getData().getList().forEach(p -> {
            if (p.get("organizing_code_string") != null && !p.get("organizing_code_string").equals("")) {
                p.put("contact_num", contactCount.getOrDefault(p.get("organizing_code_string").toString(), 0));
            } else {
                p.put("contact_num", 0);
            }
        });
        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.BUILDING.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("id") != null && opptyStatus.containsKey(r.get("id").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("id").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });

        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

    public FieldsSetting loadSearchSupplierFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "search_supplier";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "主键id", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_id", groupName, "供应商ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_name", groupName, "供应商名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_nameHL", groupName, "供应商名称(高亮)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "建设单位信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_logo", groupName, "建设单位logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("legal_name", groupName, "企业法人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("regist_capi", groupName, "注册资金", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("establish_date", groupName, "成立时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("term_start", groupName, "营业开始时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("term_end", groupName, "营业结束时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("status", groupName, "经营状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("enterprise_nature", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("scope", groupName, "经营范围", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("category", groupName, "服务分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "企业地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("number_of_employees", groupName, "公司规模", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("company_profile", groupName, "公司简介", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("coop_cnt", groupName, "总合作项目", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contact_cnt", groupName, "联系人数", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("coop_amt", groupName, "总合作金额", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_and_city", groupName, "省份城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tags", groupName, "标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_area", groupName, "项目所在区域", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_start_time", groupName, "合作项目开始时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_end_time", groupName, "合作项目结束时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("keyword", groupName, "关键词，自定义组件时忽略", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category", groupName, "行业分类(1类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_big", groupName, "行业分类(2类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_middle", groupName, "行业分类(3类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("industry_category_small", groupName, "行业分类(4类)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_province_code", groupName, "项目省份code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_city_code", groupName, "项目城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_time", groupName, "项目时间", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadSearchSupplierData(LoadDataParams options) {
        SearchSupplierRequestDto dto = new SearchSupplierRequestDto();
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());

        //找供应商暂时不支持省市多选,所以先把area设置为空
        dto.setArea("");

        OpensearchClientService service = opensearchClientFactoryService.getOpensearchService();
        OpenSearchListResponseDto res = service.searchSupplier(dto);
        ListDataResult result = new ListDataResult();
        if (res.getData() == null || res.getData().getList() == null) {
            result.setData(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        List<String> idList = new ArrayList<>();
        res.getData().getList().forEach(p -> {
            if (p.get("organizing_code") != null) {
                idList.add(p.get("organizing_code").toString());
            }
            supplierService.processSupplier(p);
            //数组转换成 json数组(建模bug)
            if (p.get("projects") != null) {
                p.put("projects", JSON.toJSONString(p.get("projects")));
            }

            if (p.get("projectSuggest") != null) {
                p.put("projectSuggest", JSON.toJSONString(p.get("projectSuggest")));
            }

            p.putIfAbsent("supplier_nameHL", "");

        });
        //数据状态
        Map<String, String> opptyStatus = commonService.getOpptyStatusBatch(CommonService.BigDataType.SUPPLIER.toString(), idList);
        res.getData().getList().forEach(r -> {
            if (r.get("organizing_code") != null && opptyStatus.containsKey(r.get("organizing_code").toString())) {
                r.put("oppty_status", opptyStatus.get(r.get("organizing_code").toString()));
            } else {
                r.put("oppty_status", "");
            }
        });
        //标签
        supplierService.processSupplierTag(res.getData().getList());
        result.setData(res.getData().getList());
        result.setTotal(res.getData().getTotal());

        return result;
    }

}